package user

import (
	"context"
	"fmt"
	"net/http"
	"wms/model"
	"wms/pkg/cryptx"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddLogic {
	return &AddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddLogic) Add(req *types.User) (resp *types.BaseResponse, err error) {
	resp = new(types.BaseResponse)

	//1.用户名是否存在
	_, err = l.svcCtx.UserModel.FindOneByName(l.ctx, req.Name)
	switch err {
	case nil: //存在
		fmt.Printf("[Error]查询用户名[%s]已存在\n", req.Name)
		resp.Code = http.StatusBadRequest
		resp.Msg = "用户名重复"
		return resp, nil
	case model.ErrNotFound: //不存在
	default: //其他错误
		fmt.Printf("[Error]查询用户名[%s]是否存在:%s\n", req.Name, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	fmt.Println("用户名称通过校验")
	//2.手机号码是否存在
	_, err = l.svcCtx.UserModel.FindOneByMobile(l.ctx, req.Mobile)
	switch err {
	case nil: //存在
		fmt.Printf("[Error]查询用户手机号码[%s]已存在\n", req.Mobile)
		resp.Code = http.StatusBadRequest
		resp.Msg = "手机号码已占用"
		return resp, nil
	case model.ErrNotFound: //不存在
	default: //其他错误
		fmt.Printf("[Error]查询用户手机号码[%s]是否存在:%s\n", req.Mobile, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//3.部门是否存在
	_, err = l.svcCtx.DepartmentModel.FindOne(l.ctx, req.DepartmentId)
	switch err {
	case nil: //存在
	case model.ErrNotFound: //不存在
		fmt.Printf("[Error]部门[%d]不存在\n", req.DepartmentId)
		resp.Code = http.StatusBadRequest
		resp.Msg = "部门不存在"
		return resp, nil
	default: //其他错误
		fmt.Printf("[Error]查询部门[%d]是否存在:%s\n", req.DepartmentId, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//4.角色是否存在
	for _, roleId := range req.RolesId {
		_, err = l.svcCtx.RoleModel.FindOne(l.ctx, roleId)
		switch err {
		case nil:
		case model.ErrNotFound:
			fmt.Printf("[Error]角色[%d]不存在\n", roleId)
			resp.Code = http.StatusBadRequest
			resp.Msg = "部分角色不存在"
			return resp, nil
		default:
			fmt.Printf("[Error]查询角色[%d]是否存在:%s\n", roleId, err.Error())
			resp.Code = http.StatusInternalServerError
			resp.Msg = "服务内部错误"
			return resp, nil
		}
	}

	//TODO: 4.生成随机密码
	password := "123456."

	//5.添加用户
	res, err := l.svcCtx.UserModel.Insert(l.ctx, &model.User{
		Name:         req.Name,
		Mobile:       req.Mobile,
		Password:     cryptx.PasswordEncrypt(l.svcCtx.Config.Salt, password),
		Status:       req.Status,
		DepartmentId: req.DepartmentId,
		Remark:       req.Remark,
	})

	if err != nil {
		fmt.Printf("[Error]添加用户[%s][%s]失败:%s\n", req.Name, req.Mobile, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	userId, err := res.LastInsertId()
	if err != nil {
		fmt.Printf("[Error]添加用户:%s\n", err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//5.录入角色
	var groupPolicies = make([][]string, 0)
	for _, roleId := range req.RolesId {
		//_, err = l.svcCtx.UserRoleModel.Insert(l.ctx, &model.UserRole{
		//			UserId: userId,
		//			RoleId: roleId,
		//		})

		groupPolicies = append(groupPolicies, []string{fmt.Sprintf("user_%d", userId), fmt.Sprintf("role_%d", roleId)})
	}
	_, err = l.svcCtx.Enforcer.AddGroupingPoliciesEx(groupPolicies)
	//l.svcCtx.Enforcer.AddNamedGroupingPoliciesEx("g", groupPolicies)
	if err != nil {
		fmt.Printf("[Error]用户[%d]分配角色:%s\n", userId, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	return resp, nil
}
